var gulp = require("gulp");
var browserify = require("browserify"); //合并捆绑成一个JavaScript文件
var source = require("vinyl-source-stream"); //将Browserify的输出文件适配成gulp能够解析的格式
var watchify = require("watchify"); //保持运行状态，并自动编译
var tsify = require("tsify"); //Browserify的一个插件
var gutil = require("gulp-util"); //压缩代码

var uglify = require("gulp-uglify"); //Uglify
var sourcemaps = require("gulp-sourcemaps"); //Uglify
var buffer = require("vinyl-buffer"); //Uglify

var paths = {
  pages: ["src/*.html"],
};

gulp.task("copy-html", function () {
  return gulp.src(paths.pages).pipe(gulp.dest("dist"));
});

var watchedBrowserify = watchify(
  browserify({
    basedir: ".",
    debug: true,
    entries: ["src/js/1/main.ts","src/js/2/2.ts"],
    cache: {},
    packageCache: {},
  }).plugin(tsify)
);

function bundle() {
  return watchedBrowserify
    .transform("babelify", {
      presets: ["es2015"],
      extensions: [".ts"],
    })
    .bundle()
    .pipe(source("bundle.js"))
    .pipe(buffer())
    .pipe(sourcemaps.init({ loadMaps: true }))
    .pipe(uglify())
    .pipe(sourcemaps.write("./"))
    .pipe(gulp.dest("dist/js"));
}

gulp.task("default", gulp.series("copy-html", bundle));

watchedBrowserify.on("update", bundle);
watchedBrowserify.on("log", gutil.log);
